﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using Uco.Models;
using System.Data;
using System.IO;
using System.Text;
using Uco.Infrastructure;

namespace Uco.Areas.Admin.Controllers
{
    [Authorize]
    public class ContactController : BaseAdminController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Details(int ID)
        {
            Contact c = SF.LoadContacts().FirstOrDefault(r => r.ID == ID);
            return View(c);
        }

        [GridAction]
        public ActionResult _AjaxIndex()
        {
            return View(new GridModel<Contact>
            {
                Data = SF.LoadContacts().OrderByDescending(r => r.ID).ToList()
            });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _AjaxDelete(int ID)
        {
            List<Contact> l = SF.LoadContacts();
            l.RemoveAll(r => r.ID == ID);
            SF.SaveContacts(l);

            return View(new GridModel<Contact>
            {
                Data = SF.LoadContacts().OrderByDescending(r => r.ID).ToList()
            });
        }

        public ActionResult CSVExport()
        {
            var items = SF.LoadContacts().OrderByDescending(r => r.ID).ToList();
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
            writer.Write("ID,");
            writer.Write("Date,");
            writer.Write("Name,");
            writer.Write("Email,");
            writer.Write("Phone,");
            writer.Write("Data,");
            writer.Write("Url,");
            writer.Write("Referal");
            writer.WriteLine();
            foreach (Contact item in items)
            {
                writer.Write(item.ID); writer.Write(","); writer.Write("\"");
                writer.Write(item.ContactDate); writer.Write("\""); writer.Write(","); writer.Write("\"");
                writer.Write(item.ContactName); writer.Write("\""); writer.Write(","); writer.Write("\"");
                writer.Write(item.ContactEmail); writer.Write("\""); writer.Write(","); writer.Write("\"");
                writer.Write(item.ContactPhone); writer.Write("\""); writer.Write(","); writer.Write("\"");
                writer.Write(item.ContactData); writer.Write("\""); writer.Write(","); writer.Write("\"");
                writer.Write(item.ContactUrl); writer.Write("\""); writer.Write(","); writer.Write("\"");
                writer.Write(item.ContactReferal); writer.Write("\""); writer.WriteLine();
            }
            writer.Flush();
            output.Position = 0;
            return File(output, "application/csv", "Contact.csv");
        }
    }
}
